package com.tools.developer.util;


import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;


public class DesUtil {

	private static final String TRANSFORMATION = "DES/CBC/PKCS5Padding";

	private static final String ALG = "DES";

	private static byte[] initializationVector = { (byte) 0x12, (byte) 0x34, (byte) 0x56,
			(byte) 0x78, (byte) 0x90, (byte) 0xAB, (byte) 0xCD, (byte) 0xEF };

	private static byte[] encrypt(String plainText, String encoding, 
			byte[] secretKey) throws Exception {
			byte[] plainBytes = plainText.getBytes(encoding);
			SecretKeySpec skeySpec = new SecretKeySpec(secretKey, ALG);
			Cipher cipher = Cipher.getInstance(TRANSFORMATION);
			IvParameterSpec iv = new IvParameterSpec(initializationVector);
			cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
			return cipher.doFinal(plainBytes);
	}
	
	public static byte[] encrypt(String plainText, byte[] secretKey) throws Exception {
		return encrypt(plainText, "UTF-8", secretKey);
	}

	private static String decrypt(byte[] cipherBytes, String encoding, 
			byte[] secretKey) throws Exception {
			SecretKeySpec skeySpec = new SecretKeySpec(secretKey, ALG);
			Cipher cipher = Cipher.getInstance(TRANSFORMATION);
			IvParameterSpec iv = new IvParameterSpec(initializationVector);
			cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
			byte[] plainText = cipher.doFinal(cipherBytes);
			return new String(plainText, encoding);
	}
	
	public static String decrypt(byte[] cipherBytes, byte[] secretKey) throws Exception {
		return decrypt(cipherBytes, "UTF-8", secretKey);
	}

}
